<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>External Template with Shadow DOM</title>
</head>
<body>
<my-shadow-element id="123"></my-shadow-element>

<script>
    // 定义自定义元素类
    class MyShadowElement extends HTMLElement {
        constructor() {
            super();

            // 创建 Shadow DOM
            const shadowRoot = this.attachShadow({ mode: 'open' });

            // 获取元素的 id 属性
            const id = this.getAttribute('id');

            // 加载外部模板文件
            fetch('template.html')
                .then(response => response.text())
                .then(html => {
                    // 解析 HTML 内容
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');

                    // 获取模板
                    const template = doc.getElementById('my-template');

                    // 克隆模板内容
                    const clone = template.content.cloneNode(true);

                    // 将 id 参数插入到模板内容中
                    const idPlaceholder = clone.querySelector('#id-placeholder');
                    if (idPlaceholder) {
                        idPlaceholder.textContent = id;
                    }

                    // 将内容附加到 Shadow DOM
                    shadowRoot.appendChild(clone);

                    // 为按钮添加事件监听器
                    const button = shadowRoot.querySelector('#my-button');
                    button.addEventListener('click', () => {
                        alert('Button clicked in Shadow DOM! ID: ' + id);
                    });
                })
                .catch(error => {
                    console.error('Error loading template:', error);
                });
        }

        // 连接生命周期回调
        connectedCallback() {
            console.log('MyShadowElement has been added to the DOM.');
        }

        disconnectedCallback() {
            console.log('MyShadowElement has been removed from the DOM.');
        }

        adoptedCallback() {
            console.log('MyShadowElement has been moved to a new document.');
        }

        attributeChangedCallback(name, oldValue, newValue) {
            console.log(`Attribute ${name} changed from ${oldValue} to ${newValue}`);
        }

        static get observedAttributes() {
            return ['id'];
        }
    }

    // 注册自定义元素
    customElements.define('my-shadow-element', MyShadowElement);
</script>
</body>
</html>